package com.iweb.education.teacher.service;

import com.iweb.education.teacher.dao.TeacherDao;
import com.iweb.education.teacher.dao.TeacherDaoImp;
import com.iweb.education.teacher.model.Teacher;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class TeacherServiceImp implements TeacherService{
    TeacherDao teacherDao = new TeacherDaoImp();
    @Override
    public boolean isLogin(String teacherusername, String teacherpassword, HttpSession session) {
        Teacher teacher = teacherDao.selectByUsernamePassword(teacherusername,teacherpassword);
        if(teacher!=null){
            session.setAttribute("teacher",teacher);
            return true;
        }else {
            return false;
        }
    }
    @Override
    public Map<String, Object> getStudentsByPage(int currentPage, int pageSize) {
        Map<String, Object> result = new HashMap<>();

        // 获取总记录数
        int totalRecords = teacherDao.getTotalStudentCount();
        // 计算总页数
        int totalPages = (int) Math.ceil((double) totalRecords / pageSize);

        // 确保当前页在有效范围内
        if (currentPage < 1) currentPage = 1;
        if (currentPage > totalPages) currentPage = totalPages;

        // 计算开始位置
        int start = (currentPage - 1) * pageSize;

        // 获取当前页数据
        List<Student> students = teacherDao.getStudentsByPage(start, pageSize);

        // 封装结果
        result.put("currentPage", currentPage);
        result.put("pageSize", pageSize);
        result.put("totalPages", totalPages);
        result.put("totalRecords", totalRecords);
        result.put("data", students);
        return result;
    }

    @Override
    public Student getStudentById(int sid) {
        return teacherDao.getStudentById(sid);
    }

    @Override
    public boolean updateStudent(Student student) {
        return teacherDao.updateStudent(student);
    }

    @Override
    public boolean deleteStudent(int sid) {
        return teacherDao.deleteStudent(sid);
    }
}
